package com.cheetah.handler;

import com.cheetah.client.CheetahClient;
import com.cheetah.listener.Callback;
import com.cheetah.protocol.Response;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ChannelHandler.Sharable
public class ClientHandler extends SimpleChannelInboundHandler<Response> {

    @Autowired
    private CheetahClient cheetahClient;

    private static Map<ChannelId,Integer> attemptsMap  = new ConcurrentHashMap();

    private Timer timer = new HashedWheelTimer();

    @Override
	protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception{
        Callback callback = (Callback)ctx.channel().attr(AttributeKey.valueOf("a")).get();
        callback.onEvent(msg);
        ctx.fireChannelRead(msg);
	}

	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.getMessage(),cause);
        ctx.close();
    }

//    @Override
//    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        int attempts = 0;
//        attemptsMap.put(ctx.channel().id(),attempts);
//        log.info("channel active,attempts={}",attempts);
//        ctx.fireChannelActive();
//    }
//
//
//    @Override
//    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
//
//        log.info("channel inactive,retry connect...");
//        int attempts = attemptsMap.get(ctx.channel().id());
//        if (attempts < 3) {
//            attempts++;
//            //重连的间隔时间会越来越长
//            int timeout = 2 << attempts;
//            try {
//                cheetahClient.getClient();
//                Thread.sleep(timeout);
//                //timer.newTimeout(this, timeout, TimeUnit.MILLISECONDS);
//            }catch (Exception e){
//                log.error(e.getMessage(),e);
//            }
//        }
//        ctx.fireChannelInactive();
//        log.info("{}{}",this.getClass().getName(),"channelInactive");
//    }
//
//    @Override
//    public void run(Timeout timeout) throws Exception {
//        cheetahClient.getClient();
//    }
}
